// import { getRouteMenusApi } from '~@/api/common/menu'
import type { UserInfo } from '~@/api/common/user'
import { getUser } from '~@/api/common/user'
import type { MenuData } from '~@/layouts/basic-layout/typing'
import { rootRoute } from '~@/router/constant'
import { generateFlatRoutes, generateRoutes } from '~@/router/generate-route'
// import { DYNAMIC_LOAD_WAY } from '~@/utils/constant'

export const useUserStore = defineStore('user', () => {
  const routerData = shallowRef()
  const menuData = shallowRef<MenuData>([])
  const userInfo = ref<UserInfo>()
  const token = useAuthorization()
  const nickname = computed(() => userInfo.value?.userName ?? userInfo.value?.userName)
  const chatStore = chatChatStore()
  /* const getMenuRoutes = async () => {
    const { data } = await getRouteMenusApi()
    return generateTreeRoutes(data ?? [])
  } */

  const generateDynamicRoutes = async () => { 
    const dynamicLoadWay =  generateRoutes
    const { menuData: treeMenuData, routeData } = await dynamicLoadWay()
    menuData.value = treeMenuData
    routerData.value = {
      ...rootRoute,
      children: generateFlatRoutes(routeData),
    }   
    return routerData.value
  }

  // 获取用户信息
  const getUserInfo = async () => {
    // 获取用户信息
    let token = localStorage.getItem('Authorization')
    if(token) {
      const { data } = await getUser(token)
      if(data.user) {
        userInfo.value = data.user
      }      
    } else {
      console.log('获取不到信息')
    }

  }

  const logout = () => {
    // 退出登录
    // 1. 清空用户信息
    token.value = null
    userInfo.value = undefined
    routerData.value = undefined
    menuData.value = []
    chatStore.updateChatMessage()
    chatStore.updateChatId(null)
  }

  return {
    userInfo,
    getUserInfo,
    logout,
    routerData,
    menuData,
    generateDynamicRoutes,
    nickname,
  }
})
